const db = require('../db/index')
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const config = require('../config')

exports.regUser = (req, res) => {
  const userinfo = req.body
  if (!userinfo.username || !userinfo.password) {
    return res.cc('用户名或密码不能为空！')
  }
  const sql = `select * from user where username=?`
  db.query(sql, userinfo.username, (err, reuslts) => {
    if (err) {
      return res.cc(err)
    }
    if (reuslts.length > 0) {
      return res.send('用户名被占用')
    }
    userinfo.password = bcrypt.hashSync(userinfo.password, 10)
    const sqlStr = `insert into user set ?`
    db.query(sqlStr, {username: userinfo.username, password: userinfo.password}, (err, results) => {
      if (err) {
        return res.cc(err)
      }
      if (results.affectedRows !== 1) {
        return res.send('注册用户失败，请稍后再试')
      }
    })
    res.send({status: 0, message: '注册成功'})
  })
}

exports.login = (req, res) => {
  const userinfo = req.body
  if (!userinfo.username || !userinfo.password) {
    return res.cc('用户名或密码不能为空！')
  }
  const sql = `select * from user where username=?`
  db.query(sql, userinfo.username, (err, results) => {
    if (err) {
      return res.cc(err)
    }
    if (results.length !== 1) {
      return res.send('登录失败')
    }
    const compareResult = bcrypt.compareSync(userinfo.password, results[0].password)
    if (!compareResult) {
      return res.cc('登录失败')
    }
    const user = { ...results[0], password: '', user_pic: '' }
    const tokenStr = jwt.sign(user, config.jwtSecretKey, {expiresIn: config.expiresIn})
    res.send({status: 0, message: '登录成功', token: 'Bearer ' + tokenStr, data: {userId: user.id}})
  })
}
